package com.hopoke.minio.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.hopoke.common.domain.ResultCodeEnum;
import com.hopoke.common.expection.CommonException;
import com.hopoke.minio.properties.MinioProperties;
import com.hopoke.minio.service.FileService;
import io.minio.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final MinioProperties minioProperties;
    @Override
    public String upload(MultipartFile file) {
        try {
            String bucketName = minioProperties.getBucketName();
            // 创建minio
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpoint())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();

            // 确认存储桶存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                System.out.println(bucketName + "Bucket已存在");
            }

            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uid = UUID.randomUUID().toString().replaceAll("-","");
            String fileName = dateDir + "/" + uid + file.getOriginalFilename();

            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .build());

            return minioProperties.getEndpoint() + "/" + bucketName + "/" + fileName;
        } catch (Exception e) {
            throw new CommonException(e, ResultCodeEnum.SERVER_ERROR);
        }
    }
}
